package entity

import (
	"os"
	"path/filepath"
	"reflect"

	. "gitee.com/night-tc/gobige/entity/props"

	"gitee.com/night-tc/gobige/logger"
)

type TypeMgr struct {
	typeMap map[string]reflect.Type
	defs    map[string]*Def
}

func newTypeMgr() (result *TypeMgr) {
	result = new(TypeMgr)
	result.typeMap = make(map[string]reflect.Type)
	result.defs = make(map[string]*Def)
	return
}

// 注册对象类型
func (mgr *TypeMgr) RegEntityType(name string, v IEntity) {
	if _, ok := mgr.typeMap[name]; ok {
		return
	}
	mgr.typeMap[name] = reflect.TypeOf(v).Elem()
}

// New对象出来
func (mgr *TypeMgr) NewEntity(name string) (result IEntity) {
	if v, ok := mgr.typeMap[name]; !ok {
		logger.Warnf("Entity type:%s not exist.", name)
		return nil
	} else {
		result = reflect.New(v).Interface().(IEntity)
	}
	return

}

/*
加载entity的配置表
协程不安全
建议在server初始化的时候，调用
*/
func (mgr *TypeMgr) LoadDefs(dirpath string) (err error) {
	_defs := make(map[string]*Def)
	err = filepath.Walk(dirpath, func(path string, f os.FileInfo, err error) error {
		if f == nil {
			return nil
		}

		if f.IsDir() {
			return nil
		}
		if def, err := LoadDef(path); def != nil {
			_defs[def.Name] = def
		} else if err != nil {
			return err
		}
		return nil
	})
	mgr.defs = _defs
	return
}

// 获取对象配置
func (mgr *TypeMgr) GetDefByName(name string) *Def {
	if result, ok := mgr.defs[name]; ok {
		return result
	} else {
		logger.Warnf("Def Type:%s not exist.", name)
		return nil
	}
}
